package ovm.gui.views.administration.users;

import com.vaadin.ui.Button;
import com.vaadin.ui.Table;
import ovm.gui.buttons.table.users.ChangeUserButton;
import ovm.gui.buttons.table.users.DeleteUserButton;
import ovm.gui.views.AbstractCatalogView;
import ovm.management.users.UserRules;

public class UserListView extends AbstractCatalogView {

    class ChangeUserButtonGenerator implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            String login = (String) source.getItem(itemId).getItemProperty("login").getValue();
            return new ChangeUserButton("Изменить", login);
        }
    }

    class DeleteUserButtonGenerator implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            String login = (String) source.getItem(itemId).getItemProperty("login").getValue();
            return new DeleteUserButton("Удалить", login);
        }
    }
    
    class RuleGenerator implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            Integer rule = (Integer) source.getItem(itemId).getItemProperty(columnId).getValue();
            return UserRules.ruleToStringMap.get(rule);
        }
    }

    @Override
    protected void buildTable() {
        table.addContainerProperty("change", Button.class, null);
        table.addGeneratedColumn("change", new ChangeUserButtonGenerator());
        table.addContainerProperty("delete", Button.class, null);
        table.addGeneratedColumn("delete", new DeleteUserButtonGenerator());
        table.addGeneratedColumn("rule", new RuleGenerator());
        table.setVisibleColumns(new Object[]{"login", "password", "rule"});
        table.setColumnHeaders(new String[]{"Логин", "Хеш пароля", "Роль"});
    }

    @Override
    protected void setContainerProperties() {
        entityContainer.addContainerProperty("id", Integer.class, null, true, true);
        entityContainer.addContainerProperty("login", String.class, "", true, true);
        entityContainer.addContainerProperty("password", String.class, "", true, true);
        entityContainer.addContainerProperty("rule", Integer.class, "", true, true);
    }

    public UserListView (Class entityClass, Boolean editable) {
        super(entityClass, editable);
        setCaption("Список пользователей");
    }

}
